<template>
	<xn-form-container title="资产历史记录" :width="500" :visible="visible" :destroy-on-close="true" @close="onClose">
		<a-row>
			<a-col :span="24">
				<a-timeline mode="left">
					<a-timeline-item v-for="item in timelineData" :key="item.id" :color="getTimelineColor(item.title)">
						<template #dot>
							<component :is="getTimelineIconComponent(item.title)" />
						</template>
						<div class="timeline-content">
							<h4>{{ item.title }}</h4>
							<p>
								<span v-for="(line, index) in formatContent(item.content)" :key="index">
									{{ line }}<br v-if="index < formatContent(item.content).length - 1" />
								</span>
							</p>
							<span class="time">{{ item.time }}</span>
						</div>
					</a-timeline-item>
				</a-timeline>
			</a-col>
		</a-row>
		<template #footer>
			<a-button @click="onClose">关闭</a-button>
		</template>
	</xn-form-container>
</template>

<script setup>
	import {
		ArrowRightOutlined,
		CheckCircleOutlined,
		CheckOutlined,
		DeleteOutlined,
		DownloadOutlined,
		RetweetOutlined,
		ToolOutlined,
		UserOutlined
	} from '@ant-design/icons-vue'
	import assetsIssueApi from '@/api/hrms/assets/issue/assetsIssueApi'

	// 默认是关闭状态
	const visible = ref(false)
	const emit = defineEmits({ successful: null })

	// 时间轴数据
	const timelineData = ref([])

	// 打开模态框
	const onOpen = (id) => {
		visible.value = true
		if (id) {
			loadTimelineData(id)
		}
	}

	// 加载时间轴数据
	const loadTimelineData = async (id) => {
		assetsIssueApi.getIssueTimeLine(id).then((res) => {
			// 为每个时间线项添加唯一ID
			timelineData.value = res.map((item, index) => ({
				...item,
				id: index + 1
			}))
		})
	}

	// 格式化内容，处理换行符
	const formatContent = (content) => {
		if (!content) return []
		return content.split(/\r\n|\n|\r/)
	}

	// 根据标题设置时间线颜色
	const getTimelineColor = (title) => {
		switch (title) {
			case '资产领用':
				return 'green'
			case '资产归还':
				return 'blue'
			case '资产报修':
				return 'orange'
			case '资产报修完成':
				return 'purple'
			case '资产报废':
				return 'red'
			case '资产调拨':
				return 'cyan'
			case '资产接收':
				return 'geekblue'
			default:
				return 'blue'
		}
	}

	// 根据标题获取时间线图标组件
	const getTimelineIconComponent = (title) => {
		switch (title) {
			case '资产领用':
				return UserOutlined
			case '资产归还':
				return RetweetOutlined
			case '资产报修':
				return ToolOutlined
			case '资产报修完成':
				return CheckOutlined
			case '资产报废':
				return DeleteOutlined
			case '资产调拨':
				return ArrowRightOutlined
			case '资产接收':
				return DownloadOutlined
			default:
				return CheckCircleOutlined
		}
	}

	// 关闭模态框
	const onClose = () => {
		visible.value = false
	}

	defineExpose({
		onOpen
	})
</script>

<style scoped>
	.timeline-content h4 {
		margin-bottom: 4px;
		font-weight: 600;
	}

	.timeline-content p {
		margin-bottom: 4px;
		color: #666;
		white-space: pre-wrap;
	}

	.time {
		font-size: 12px;
		color: #999;
	}
</style>
